<template>
  <view class="waterfall-container">
    <view class="waterfall-content">
      <view
        class="waterfall-column"
        v-for="(column, columnIndex) in columns"
        :key="columnIndex"
        :style="{
          width: columnWidth,
        }"
      >
        <view
          class="waterfall-item"
          v-for="(item, itemIndex) in column"
          :key="item.id || itemIndex"
          @tap="onItemClick(item)"
        >
          <slot name="item" :item="item"></slot>
        </view>
      </view>
    </view>

    <view class="waterfall-footer" v-if="!finished" @tap="onLoadMore">
      <slot name="footer">
      </slot>
    </view>
  </view>
</template>

<script>
export default {
  name: "WaterfallFlow",
  props: {
    // 数据列表
    list: {
      type: Array,
      default: () => [],
    },
    // 列数
    columnCount: {
      type: Number,
      default: 2,
    },
    // 列宽
    columnWidth: {
      type: String,
      default: "48%",
    },
    // 列间距
    columnGap: {
      type: Number,
      default: 10,
    },
    // 是否正在加载
    loading: {
      type: Boolean,
      default: false,
    },
    // 是否已加载完成
    finished: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      columns: [],
    }
  },
  watch: {
    list: {
      handler(newVal) {
        this.distributeItems(newVal)
      },
      deep: true,
    },
  },
  mounted() {
    this.distributeItems(this.list)
  },
  methods: {
    // 分配数据到各列
    distributeItems(items) {
      // 初始化列
      const columns = Array.from({ length: this.columnCount }, () => [])

      // 分配数据
      items.forEach((item, index) => {
        // 找出当前高度最小的列
        const minHeightIndex = this.getMinHeightColumnIndex(columns)
        columns[minHeightIndex].push(item)
      })

      this.columns = columns
    },

    // 获取当前高度最小的列索引
    getMinHeightColumnIndex(columns) {
      // 简单实现：按照项目数量分配
      const columnHeights = columns.map((column) => column.length)
      return columnHeights.indexOf(Math.min(...columnHeights))
    },

    // 点击项目
    onItemClick(item) {
      this.$emit("itemClick", item)
    },

    // 加载更多
    onLoadMore() {
      if (!this.loading && !this.finished) {
        this.$emit("loadmore")
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.waterfall-container {
  width: 100%;
  padding: 0 10px;
  box-sizing: border-box;
}

.waterfall-content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.waterfall-column {
  display: flex;
  flex-direction: column;
}

.waterfall-footer {
  text-align: center;
  padding: 20px 0;
  color: #999;
  font-size: 14px;
}
</style>
